package com.wisemoresystem.seal.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.ne.framework.data.page.Page;
import org.ne.framework.data.task.Task;
import org.ne.framework.data.util.ChkTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wisemoresystem.seal.base.service.BaseService;
import com.wisemoresystem.seal.model.t_check;
import com.wisemoresystem.seal.model.t_early_warning;
import com.wisemoresystem.seal.model.t_seal;
import com.wisemoresystem.seal.model.t_seal_push;
import com.wisemoresystem.seal.util.DateTools;
import com.wisemoresystem.seal.util.SpringTools;
import com.wisemoresystem.seal.web.WebTools;

/**
 * 印章领取
 * @author hxj
 *
 */
@Service
public class SealRecieveService extends BaseService {
	
	@Autowired
	private VerifyConfigService configService;
	
	@Task(code = "seal_distribution4", tip = "未完成的印章领取(@cnt)")
	public long selectDistributeRecieveList() {
		String sql = "select count(*) cnt from t_seal t "
				+ " join t_seal_push tp on tp.seal_id=t._id "
				+ " where t.status=0 and tp.down_bank_id=? and tp.identifying_code is null and t.flag_stop='下发停用' and t.flag='下发中' and tp.flag='通过' ";

		Long cnt = super.getTaskCnt(sql,WebTools.getCurrentBankId());
				
		return cnt;
	}
	
	//领取列表
	public List<Map<String, Object>> selectDistributeRecieveList(String bank_id,String srh_name,Page page){
		
		String sql="select t.*,tb.name bank_name,tn.title,tc.name config_name,tp._id push_id from t_seal t "
				+ " join t_seal_push tp on tp.seal_id=t._id "
				+ " left join t_seal_new tn on t.seal_new_id=tn._id "
				+ "	left join t_seal_type_config tc on tn.seal_type_config_id=tc._id "
				+ " left join t_bank tb on t.bank_id=tb._id "
				+ " where t.status=0 and tp.down_bank_id=? and t.flag_stop='下发停用' "
				+ " and t.flag='下发中' and t.true_code like ? and tp.identifying_code is null and tp.flag='通过' order by t.created asc";
		List<String> params = new ArrayList<String>();
		params.add(bank_id);
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and t.true_code like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}
		List<Map<String, Object>> list = jc.queryForList(sql,params.toArray(), page);
		return list;
	}

	//领取
	@Transactional
	public boolean recieve(String push_id,t_seal_push push,String msg,String save_user_id,t_early_warning warning) {
		
		t_seal_push p = super.findObjById(push_id, t_seal_push.class);
		p.setRecieve_note(push.getRecieve_note());
		p.setRecieve_time(new Timestamp(System.currentTimeMillis()));
		p.setRecieve_user_id(WebTools.getCurrentUserId());
		if("giveup".equals(msg)){
			p.setFlag("不通过");
		}
		super.updateObj(p);
		
		if(ChkTools.isNotNull(warning.getReason())){
			warning.setSeal_id(p.getSeal_id());
			warning.setPush_bank_id(p.getBank_id());
			warning.setPush_time(p.getVerify_time());
			warning.setRecieve_bank_id(p.getDown_bank_id());
			warning.setRecieve_time(new Timestamp(System.currentTimeMillis()));
			warning.setUser_id(WebTools.getCurrentUserId());
			super.saveObj(warning);
		}
			
		if("giveup".equals(msg)){
			t_seal seal = super.findObjById(p.getSeal_id(), t_seal.class);
			seal.setSave_user_id(save_user_id);
			seal.setFlag("印章出错");
			seal.setRecieve_user_id(WebTools.getCurrentUserId());
			super.updateObj(seal);
			
			errorCheck(p);
			
			return true;
		}

		t_seal seal = super.findObjById(p.getSeal_id(), t_seal.class);
		seal.setFlag("领取中");
		seal.setSave_user_id(save_user_id);
		seal.setRecieve_user_id(WebTools.getCurrentUserId());
		super.updateObj(seal);
		
		myRecieveSubmit(p);
		return true;
	}
	
	@Transactional
	private void myRecieveSubmit(t_seal_push push) {

		boolean isVerify = configService.isGetStart();
		if (isVerify == true) {
			t_check check = new t_check();
			check.setBank_id(WebTools.getCurrentBankId());
			check.setType("印章领用复核");
			check.setIs_verify("是");
			check.setVerify("待审核");
			check.setUser_id(WebTools.getCurrentUserId());
			super.saveObj(check);
			
			push.setRe_check_id(check.get_id());
			push.setFlag("领取待审核");
			super.updateObj(push);
			
		}else{
			push.setFlag("领取通过");
			super.updateObj(push);
			
			t_seal seal = super.findObjById(push.getSeal_id(), t_seal.class);
			seal.setFlag("停用");
			seal.setFlag_stop("暂时停用");
			super.updateObj(seal);
		}
	}
	
	@Task(code = "seal_in", tip = "未完成的印章入库(@cnt)")
	public long selectDistributeRecieveInList() {
		String sql = "select count(*) cnt from t_seal t "
				+ " join t_seal_push tp on tp.seal_id=t._id "
				+ " where t.status=0 and t.bank_id=? and t.flag_stop='下发停用' and t.flag='下发中' and tp.flag='在途' ";

		Long cnt = super.getTaskCnt(sql,WebTools.getCurrentBankId());
		
		return cnt;
	}
	
	//入库列表
	public List<Map<String, Object>> selectDistributeRecieveInList(String bank_id,String srh_name,Page page){
		
		String sql="select t.*,tb.name bank_name,tn.title,tc.name config_name,tp._id push_id from t_seal t "
				+ " join t_seal_push tp on tp.seal_id=t._id "
				+ " left join t_seal_new tn on t.seal_new_id=tn._id "
				+ "	left join t_seal_type_config tc on tn.seal_type_config_id=tc._id "
				+ " left join t_bank tb on t.bank_id=tb._id "
				+ " where t.status=0 and t.bank_id=? and t.flag_stop='下发停用' "
				+ " and t.flag='下发中' and t.true_code like ? and tp.flag='在途' order by t.created asc";
		List<String> params = new ArrayList<String>();
		params.add(bank_id);
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and t.true_code like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}
		List<Map<String, Object>> list = jc.queryForList(sql,params.toArray(), page);
		return list;
	}
		
	@Task(code = "seal_distribution5", tip = "未完成的印章领取复核(@cnt)")
	public long selectDistributeRecieveCheckList() {
		String sql = "select count(*) cnt from t_seal t "
				+ " join t_seal_push tp on tp.seal_id=t._id "
				+ " where t.status=0 and t.bank_id=? and t.recieve_user_id!=? and t.flag_stop='下发停用' and t.flag='领取中' and tp.flag='领取待审核' ";

		Long cnt = super.getTaskCnt(sql,WebTools.getCurrentBankId(),WebTools.getCurrentUserId());
		
		return cnt;
	}
	
	//领取审核列表
	public List<Map<String, Object>> selectDistributeRecieveCheckList(String bank_id,String srh_name,Page page){
		
		String sql="select t.*,tb.name bank_name,tn.title,tc.name config_name,tp._id push_id from t_seal t "
				+ " join t_seal_push tp on tp.seal_id=t._id "
				+ " left join t_seal_new tn on t.seal_new_id=tn._id "
				+ "	left join t_seal_type_config tc on tn.seal_type_config_id=tc._id "
				+ " left join t_bank tb on t.bank_id=tb._id "
				+ " where t.status=0 and t.bank_id=? and t.flag_stop='下发停用' and t.recieve_user_id!=? "
				+ " and t.flag='领取中' and t.true_code like ? and tp.flag='领取待审核' order by t.created asc";
		List<String> params = new ArrayList<String>();
		params.add(bank_id);
		params.add(WebTools.getCurrentUserId());
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and t.true_code like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}
		List<Map<String, Object>> list = jc.queryForList(sql,params.toArray(), page);
		return list;
	}

	@Transactional
	public boolean check(String push_id, t_check check) {
		
		t_seal_push push = super.findObjById(push_id, t_seal_push.class);
		
		t_check tc = super.findObjById(push.getRe_check_id(), t_check.class);
		
		t_seal seal = super.findObjById(push.getSeal_id(), t_seal.class);
		if("通过".equals(check.getVerify())){
			seal.setFlag("停用");
			seal.setFlag_stop("暂时停用");
			push.setFlag("领取通过");
		}else{
			seal.setFlag("印章出错");
			push.setFlag("不通过");
		}
		super.updateObj(seal);
		super.updateObj(push);
		
		if("印章出错".equals(seal.getFlag()))
			errorCheck(push);
		
		tc.setVerify(check.getVerify());
		tc.setVerify_bank_id(WebTools.getCurrentBankId());
		tc.setVerify_time(new Timestamp(System.currentTimeMillis()));
		tc.setVerify_user_id(WebTools.getCurrentUserId());
		tc.setNote(check.getNote());
		super.updateObj(tc);
		
		return true;
	}
	
	@Transactional
	public void errorCheck(t_seal_push push){
		
		boolean isVerify = configService.isGetUnMatchStart();
		if (isVerify == true) {
			t_check check = new t_check();
			check.setBank_id(WebTools.getCurrentBankId());
			check.setType("领用不符复核");
			check.setIs_verify("是");
			check.setVerify("待审核");
			check.setUser_id(WebTools.getCurrentUserId());
			super.saveObj(check);
			
			push.setTwice_check_id(check.get_id());
			push.setFlag("不符待审核");
			super.updateObj(push);
			
		}else{
			push.setFlag("不通过");
			super.updateObj(push);
			
			t_seal seal = super.findObjById(push.getSeal_id(), t_seal.class);
			seal.setFlag("印章出错");
			seal.setFlag_stop("暂时停用");
			super.updateObj(seal);
		}
		
	}
	
	@Task(code = "seal_distribution6", tip = "未完成的印章不符复核(@cnt)")
	public long selectDistributeRecieveTwiceList() {
		String sql = "select count(*) cnt from t_seal t "
				+ " join t_seal_push tp on tp.seal_id=t._id "
				+ " where t.status=0 and t.bank_id=? and t.save_user_id!=? and t.flag_stop='下发停用' and t.flag='印章出错' and tp.flag='不符待审核' ";

		Long cnt = super.getTaskCnt(sql,WebTools.getCurrentBankId(),WebTools.getCurrentUserId());
		
		return cnt;
	}
	
	//印章不符列表
	public List<Map<String, Object>> selectDistributeRecieveTwiceList(String bank_id,String srh_name,Page page){
		
		String sql="select t.*,tb.name bank_name,tn.title,tc.name config_name,tp._id push_id from t_seal t "
				+ " join t_seal_push tp on tp.seal_id=t._id "
				+ " left join t_seal_new tn on t.seal_new_id=tn._id "
				+ "	left join t_seal_type_config tc on tn.seal_type_config_id=tc._id "
				+ " left join t_bank tb on t.bank_id=tb._id "
				+ " where t.status=0 and t.bank_id=? and t.flag_stop='下发停用' and t.save_user_id!=? " 
				+ " and t.flag='印章出错' and t.true_code like ? and tp.flag='不符待审核' order by t.created asc";
		List<String> params = new ArrayList<String>();
		params.add(bank_id);
		params.add(WebTools.getCurrentUserId());
		if (ChkTools.isNull(srh_name)) {
			sql = sql.replace("and t.true_code like ?", "");
		} else {
			params.add("%" + srh_name + "%");
		}
		List<Map<String, Object>> list = jc.queryForList(sql,params.toArray(), page);
		return list;
	}

	//不符复核
	@Transactional
	public boolean twice(String push_id, t_check check) {
		
		t_seal_push push = super.findObjById(push_id, t_seal_push.class);
		push.setTwice_note(push.getVerify_note());
		push.setTwice_user_id(WebTools.getCurrentUserId());
		push.setTwice_time(new Timestamp(System.currentTimeMillis()));
		push.setTwice_note(check.getNote());
		super.updateObj(push);
		
		t_check tc = super.findObjById(push.getTwice_check_id(), t_check.class);
		
		t_seal seal = super.findObjById(push.getSeal_id(), t_seal.class);
		seal.setFlag_stop("暂时停用");
		if("通过".equals(check.getVerify())){
			seal.setFlag("印章出错");
			push.setFlag("不通过");
		}else{
			seal.setFlag("停用");
			push.setFlag("领取通过");
		}
		super.updateObj(seal);
		super.updateObj(push);
		
		tc.setVerify(check.getVerify());
		tc.setVerify_bank_id(WebTools.getCurrentBankId());
		tc.setVerify_time(new Timestamp(System.currentTimeMillis()));
		tc.setVerify_user_id(WebTools.getCurrentUserId());
		tc.setNote(check.getNote());
		super.updateObj(tc);
		
		return true;
	}

	public String getIdentifyingCode() {
		String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";   
	    Random random = new Random();   
	    StringBuffer sb = new StringBuffer();   
	    for (int i = 0; i < 8; i++) {   
	        int number = random.nextInt(base.length());   
	        sb.append(base.charAt(number));   
	    }   
	    return sb.toString();   
	}
	
	public static void main(String[] args) {
		SealRecieveService s = SpringTools.getBean(SealRecieveService.class);
		System.err.println(s.selectIndentifyCodeList("4028814a4ae1e830014ae22b9a3c005d",null));
	}

	@Transactional
	public boolean apply(String push_id, t_seal_push push) {
		t_seal_push p = super.findObjById(push_id, t_seal_push.class);
		p.setP_id(push.getP_id());
		p.setPerson(push.getPerson());
		p.setM_id(push.getM_id());
		p.setMen(push.getMen());
		p.setIdentifying_code(push.getIdentifying_code());
		p.setCode_time(new Timestamp(System.currentTimeMillis()));
		p.setRec_app_user_id(WebTools.getCurrentUserId());
		super.updateObj(p);
		
		return true;
	}

	public List<Map<String, Object>> selectIndentifyCodeList(
			String bank_id, String srh_name) {
		String sql = "select t.code_time,t.identifying_code,ts.*,tn.title,tc.name config_name,"
				+ " tb.name bank_name from t_seal_push t "
				+ " left join t_seal ts on t.seal_id=ts._id "
				+ " left join t_seal_new tn on ts.seal_new_id=tn._id "
				+ "	left join t_seal_type_config tc on tn.seal_type_config_id=tc._id "
				+ " left join t_bank tb on t.bank_id=tb._id "
				+ " where t.status=0 and t.down_bank_id=? and t.identifying_code is not null "
				+ " and t.code_time>=? and t.code_time<=? ";
		List<String> params = new ArrayList<String>();
		params.add(bank_id);
		params.add(srh_name);
		params.add(DateTools.addOneDay(srh_name));
		List<Map<String, Object>> list = jt.queryForList(sql,params.toArray());
		return list;
	}
}
